// ------------------------ 获取分数，展示列表 -----------------
function getScoreList() {
  axios.get('/score/list').then(({data: {code, data, message}}) => {
    if (code === 0) {
      let html = ''
      for (let k in data) {
        html += `
        <tr>
          <th scope="row">${k}</th>
          <td>${data[k].name}</td>
          <td data-batch="1" data-id="${k}" class="score">${data[k].score[0]}</td>
          <td data-batch="2" data-id="${k}" class="score">${data[k].score[1]}</td>
          <td data-batch="3" data-id="${k}" class="score">${data[k].score[2]}</td>
          <td data-batch="4" data-id="${k}" class="score">${data[k].score[3]}</td>
          <td data-batch="5" data-id="${k}" class="score">${data[k].score[4]}</td>
        </tr>
        `
      }
      qs('tbody').innerHTML = html
    }
  })
}
getScoreList()

// ------------------------ 可编辑的表格 -----------------------
qs('tbody').onclick = function (e) {
  let score = e.target.classList.contains('score')
  if (score) {
    // 创建一个td
    let td = e.target
    if (td.querySelector('input')) return
    let text = td.innerText // 保存td的分数
    td.innerHTML = '' // 设置 td 内容为空

    // 动态创建 input
    let input = document.createElement('input')
    input.value = text
    td.appendChild(input)
    input.focus() // 获取焦点

    let isEditOk = false // 记录编辑状态

    // 注册键盘摁下事件
    input.onkeydown = function (e) {
      if (e.key === 'Enter') {
        let stu_id = td.dataset.id
        let batch = td.dataset.batch
        let score = input.value
        if (isNaN(score) || score < 0 || score > 100) {
          return alert('请输入0-100之间的数字')
        }
        axios.post('/score/entry', {
          stu_id,
          batch,
          score
        }).then(({data: {code, message}}) => {
          if(code === 0) {
            alert(message)
            isEditOk = true
            td.innerHTML = score
          }
        })
      }
    }

    // 注册失去焦点
    input.onblur = function () {
      if(!isEditOk) {
        td.innerHTML = text // 如果没有编辑设置为原来的内容
      }
    }
  }
}